package com.lin.consumer;

import com.lin.util.RabbitUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class Demo1Consumer {

    private static String QUEUE_NAME;

    @Value("${queue.hello_queue_name}")
    public void  setQueueName(String queueName) {
        QUEUE_NAME = queueName;
    }

    public static void work(Integer id) throws IOException {
        Connection connection = RabbitUtil.getConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME,false,false,false,null);

        System.out.println("Hello_Consumer" + id + " start waiting for message");

        DeliverCallback deliverCallback = (consumerTag,delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println("Hello_Consumer"+ id +" received: " + message);
        };
//        注册消费回调
        channel.basicConsume(QUEUE_NAME,true,deliverCallback,consumerTag -> {});
    }
}
